#!/usr/bin/env python3
"""
MySQL MCP Server PyInstaller 打包工具
简化版本，避免SSL库冲突
"""

import os
import sys
import subprocess
import shutil
from pathlib import Path

def check_dependencies():
    """检查必要的依赖"""
    print("检查依赖...")
    
    try:
        import PyInstaller
        print(f"✓ PyInstaller 已安装: {PyInstaller.__version__}")
    except ImportError:
        print("✗ PyInstaller 未安装，正在安装...")
        subprocess.run([sys.executable, "-m", "pip", "install", "pyinstaller"], check=True)
        print("✓ PyInstaller 安装完成")

def create_simple_spec():
    """创建简化的spec文件"""
    project_root = Path.cwd()
    main_file = project_root / "src" / "mysql_mcp_server" / "main.py"
    exe_name = "mysql-mcp-server"
    
    print("创建简化 spec 文件...")
    
    # 简化的spec文件，避免SSL冲突
    spec_content = f'''# -*- mode: python ; coding: utf-8 -*-

a = Analysis(
    ['{main_file}'],
    pathex=['{project_root}'],
    binaries=[],
    datas=[],
    hiddenimports=[
        'mysql_mcp_server',
        'mysql_mcp_server.config',
        'mysql_mcp_server.mcp_server', 
        'mysql_mcp_server.logger',
        'mysql_mcp_server.query_engine',
        'mysql_mcp_server.server',
        'mysql_mcp_server.query_table_info',
        'mcp.server',
        'mcp.types',
        'mysql.connector',
        'asyncio',
        'json',
        'logging',
    ],
    hookspath=[],
    hooksconfig={{}},
    runtime_hooks=[],
    excludes=[
        'tkinter',
        'matplotlib', 
        'numpy',
        'scipy',
        'pandas',
        'PIL',
        'PyQt5',
        'PyQt6',
        'wx',
    ],
    win_no_prefer_redirects=False,
    win_private_assemblies=False,
    cipher=None,
    noarchive=False,
)

pyz = PYZ(a.pure, a.zipped_data, cipher=None)

exe = EXE(
    pyz,
    a.scripts,
    [],
    exclude_binaries=True,
    name='{exe_name}',
    debug=False,
    bootloader_ignore_signals=False,
    strip=False,
    upx=True,
    console=True,
    disable_windowed_traceback=False,
    argv_emulation=False,
    target_arch=None,
    codesign_identity=None,
    entitlements_file=None,
)

coll = COLLECT(
    exe,
    a.binaries,
    a.zipfiles,
    a.datas,
    strip=False,
    upx=True,
    upx_exclude=[],
    name='{exe_name}',
)
'''
    
    spec_file = project_root / f"{exe_name}.spec"
    with open(spec_file, 'w', encoding='utf-8') as f:
        f.write(spec_content)
    
    print(f"✓ 创建 spec 文件: {spec_file}")
    return spec_file

def build_executable(spec_file):
    """构建可执行文件"""
    print("开始构建可执行文件...")
    
    # 清理旧的构建文件
    for dir_name in ['build', 'dist']:
        if os.path.exists(dir_name):
            print(f"✓ 清理 {dir_name} 目录")
            shutil.rmtree(dir_name)
    
    # 构建
    cmd = [sys.executable, "-m", "PyInstaller", "--clean", str(spec_file)]
    print(f"执行命令: {' '.join(cmd)}")
    
    result = subprocess.run(cmd, capture_output=True, text=True)
    
    if result.returncode == 0:
        print("✓ 构建成功!")
        
        # 检查生成的文件
        dist_dir = Path("dist")
        if dist_dir.exists():
            exe_files = list(dist_dir.rglob("mysql-mcp-server*"))
            if exe_files:
                exe_file = exe_files[0]
                if exe_file.is_file():
                    size_mb = exe_file.stat().st_size / (1024 * 1024)
                    print(f"✓ 可执行文件: {exe_file} ({size_mb:.1f} MB)")
                    
                    # 设置执行权限
                    os.chmod(exe_file, 0o755)
                    print("✓ 设置执行权限")
                    
                    return exe_file
        
        print("⚠ 未找到生成的可执行文件")
        return None
    else:
        print("✗ 构建失败!")
        print("错误输出:")
        print(result.stderr)
        return None

def create_startup_script(exe_file):
    """创建启动脚本"""
    if not exe_file:
        return
        
    script_content = f'''#!/bin/bash
# MySQL MCP Server 启动脚本

# 设置环境变量（如果需要）
# export MYSQL_HOST=localhost
# export MYSQL_PORT=3306
# export MYSQL_USER=your_user
# export MYSQL_PASSWORD=your_password
# export MYSQL_DATABASE=your_database

# 启动服务器
exec "{exe_file.absolute()}" "$@"
'''
    
    script_file = Path("run-mysql-mcp-server.sh")
    with open(script_file, 'w', encoding='utf-8') as f:
        f.write(script_content)
    
    os.chmod(script_file, 0o755)
    print(f"✓ 创建启动脚本: {script_file}")

def create_ide_config(exe_file):
    """创建IDE配置文件"""
    if not exe_file:
        return
        
    config_content = f'''{{
  "mcpServers": {{
    "mysql-mcp-server": {{
      "command": "{exe_file.absolute()}",
      "args": [],
      "env": {{
        "MYSQL_HOST": "localhost",
        "MYSQL_PORT": "3306",
        "MYSQL_USER": "your_user", 
        "MYSQL_PASSWORD": "your_password",
        "MYSQL_DATABASE": "your_database"
      }}
    }}
  }}
}}'''
    
    config_file = Path("mcp-server-config-executable.json")
    with open(config_file, 'w', encoding='utf-8') as f:
        f.write(config_content)
    
    print(f"✓ 创建IDE配置文件: {config_file}")

def main():
    """主函数"""
    print("=== MySQL MCP Server PyInstaller 打包工具（简化版） ===\n")
    
    try:
        # 检查依赖
        check_dependencies()
        
        # 创建spec文件
        spec_file = create_simple_spec()
        
        # 构建可执行文件
        exe_file = build_executable(spec_file)
        
        # 创建启动脚本
        create_startup_script(exe_file)
        
        # 创建IDE配置
        create_ide_config(exe_file)
        
        print("\n=== 打包完成 ===\n")
        
        if exe_file:
            print("生成的文件:")
            print(f"  - {exe_file} (可执行文件目录)")
            print(f"  - run-mysql-mcp-server.sh (启动脚本)")
            print(f"  - mcp-server-config-executable.json (IDE配置)")
            
            print("\n使用方法:")
            print(f"  1. 目录运行: ./dist/mysql-mcp-server/mysql-mcp-server")
            print(f"  2. 使用启动脚本: ./run-mysql-mcp-server.sh")
            print(f"  3. IDE配置: 使用 mcp-server-config-executable.json")
            
            print("\n注意: 请确保设置正确的数据库连接信息")
        else:
            print("打包失败，请检查错误信息")
            return 1
            
    except Exception as e:
        print(f"✗ 打包过程中出现错误: {e}")
        return 1
    
    return 0

if __name__ == "__main__":
    sys.exit(main())